package demo.controler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import demo.model.AddressBook;
import demo.model.Contact;
import demo.model.ContactObserver;

public class AddressBookControler {
	AddressBook book;
	ArrayList<ContactObserver> observers;

	public AddressBookControler(AddressBook book) {
		this.book = book;
		observers = new ArrayList<ContactObserver>();
	}

	public void addObserver(ContactObserver newObserver) {
		observers.add(newObserver);
	}

	public void updateContact(Contact contact) {
		for (ContactObserver obs : observers) {
			obs.updateContact(contact, book);
		}
	}

	public Contact[] getContacts() {
		return book.getContacts();
	}

	public Contact createContact(String first, String last, String phone) {
		Contact contact = new Contact(book, first, last, phone);
		book.addContact(contact);
		updateContact(contact);
		return contact;
	}

	public ContactModifier getContactUpdater(final Contact contact) {
		return new ContactModifier() {

			@Override
			public void modify(String first, String last, String phone) {
				contact.setInformations(first, last, phone);
				updateContact(contact);
				System.out.println(contact);
			}
		};
	}

	public ContactModifier getContactCreator() {
		return new ContactModifier() {

			@Override
			public void modify(String first, String last, String phone) {
				createContact(first, last, phone);
			}
		};
	}

	public void loadFromFile(File file) throws IOException {
		BufferedReader is = new BufferedReader(new FileReader(file));
		try {
			while (is.ready())
				book.addContact(readContactFromFile(is));
		} catch (EOFException e) {
		}
		is.close();
		updateContact(null);
	}

	public void saveToFile(File file) throws IOException,
			ClassNotFoundException {
		BufferedWriter os = new BufferedWriter(new FileWriter(file));
		for (Contact contact : book.getContacts()) {
			writeContactToFile(os, contact);
		}
		os.flush();
		os.close();
		updateContact(null);
	}

	private Contact readContactFromFile(BufferedReader is) throws IOException {
		String objFirst = is.readLine();
		String objName = is.readLine();
		String objPhone = is.readLine();
		return new Contact(book, objFirst, objName, objPhone);
	}

	private void writeContactToFile(BufferedWriter os, Contact contact)
			throws IOException {
		os.write(contact.getFirstName() + "\n");
		os.write(contact.getLastName() + "\n");
		os.write(contact.getPhoneNumber() + "\n");
	}
}
